﻿#include "loggerqdebug.h"
#include "src/config/globals.h"
#include <QDateTime>
#include <QDebug>
#include <QDir>
#include <QFileInfo>
#include <iostream>
static QString g_LogPath;
static QFile   g_File;
LoggerQDebug::LoggerQDebug(QObject* parent)
    : BasicLogger(parent)
{
    qInstallMessageHandler(handle);

    QString path = filePath();
    g_LogPath    = path;
    QFileInfo info(path);

    QDir dir(info.absolutePath());
    if (!dir.exists()) {
        if (!dir.mkpath(info.path())) { qDebug() << "create log file error!" << endl; }
        else {
            g_File.setFileName(path);
            g_File.open(QIODevice::WriteOnly | QIODevice::Append);
        }
    }
    else {

        g_File.setFileName(path);
        g_File.open(QIODevice::WriteOnly | QIODevice::Append);
    }
}

LoggerQDebug::~LoggerQDebug()
{

    g_File.close();
}

void LoggerQDebug::print(const QString& file, int line, const QString& func, void* tid, int level,
                         const QVariant& var, bool up)
{
    QDateTime dt;
    QString   dtStr    = dt.currentDateTime().toString(Qt::ISODate);
    quint64   threadId = reinterpret_cast<quint64>(tid);
    QString   threadIdStr =
        QString::number(threadId, 16).toUpper();   // 转换为十六进制字符串并转为大写
    QString front =
        QString::fromLocal8Bit("%1[%2][%3] %4:%5 %6 -")
            .arg(dtStr, GLOBAL::LOG_NAMES[level], threadIdStr, file, QString::number(line), func);
    front = front.replace("..\\", "");
    qDebug() << front.toLocal8Bit().data()
             << var;   // 使用qDebug而不是直接存文件，是为了打印QVariant类型
}

void LoggerQDebug::handle(QtMsgType type, const QMessageLogContext& contex, const QString& msg)
{

    QString path = filePath();
    if (g_LogPath.compare(path) != 0) {
        g_LogPath = path;
        g_File.close();
        g_File.setFileName(path);
        g_File.open(QIODevice::WriteOnly | QIODevice::Append);
    }
    QString key("QVariant(");
    QString message = msg;
    if (msg.indexOf(key) != -1) { message.replace(msg.indexOf(key), key.size(), "").chop(1); }


    if (g_File.isOpen()) {
        // 输入到文件流中
        QTextStream stream(&g_File);
        stream << message << endl;
    }
    // 用于控制台输出
    std::cout << message.toLocal8Bit().data() << std::endl;
}
